import React, { useState, useRef } from 'react';
import { Card, Col, Row, Statistic, Space, Tag, Tabs } from 'antd';
// import { ReloadOutlined } from '@ant-design/icons';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { MyContent } from '@/components/MyUI';
import * as api from '@/services/report';
import * as utils from '@/utils/utils';
import {
  LightFilter,
  ProFormDatePicker,
  ProFormInstance,
  ProFormSwitch,
} from '@ant-design/pro-form';
import moment from 'moment';
import { useModel } from 'umi';
import { ReloadOutlined } from '@ant-design/icons';
import Countdown from 'antd/lib/statistic/Countdown';

// const renderBadge = (count: number, total?: number, active = false) => {
//   let display = total ? `${count}/${total}` : count;
//   return (
//     <Badge
//       count={display}
//       overflowCount={9999}
//       showZero
//       style={{
//         marginTop: -4,
//         marginLeft: 2,
//         color: active ? '#1890FF' : '#999',
//         backgroundColor: active ? '#E6F7FF' : '#eee',
//       }}
//     />
//   );
// };

const List: React.FC = () => {
  const { hasRight } = useModel('useAuthModel');
  if (!hasRight('report_userstat')) {
    return <></>;
  }

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [countdownTicks, setCountdownTicks] = useState<number>(
    Date.now() + 60000,
  );

  // const dayTabs = [{tab:"今天", key:"0"},{tab:"昨天", key:"1"},{tab:"前天", key:"2"},{tab:"3天前", key:"3"},{tab:"4天前", key:"4"},{tab:"5天前", key:"5"},{tab:"6天前", key:"6"},{tab:"7天前", key:"7"},]

  const [data, setData] = useState<API.ActiveStatList | undefined>(undefined);
  const [preTodayRegistCount, setPreTodayRegistCount] = useState<
    number | undefined
  >(undefined);
  const [activeGenre, setActiveGenre] = useState<string | undefined>('regist');
  const [statDay, setStatDay] = useState<string | undefined>(
    moment(new Date()).format('yyyy-MM-DD'),
  );
  const [statHour, setStatHour] = useState<boolean | undefined>(false);
  const [statAllType, setStatAllType] = useState<string | undefined>('1');
  // const [subTabData, setSubTabData] = useState<any>(dayTabs);
  // const [activeDay, setActiveDay] = useState<string | undefined>("0");

  const reload = () => {
    actionRef.current?.reload();
    setCountdownTicks(Date.now() + 60000);
  };

  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {
    const result = await api.activeStat(params, sorter, filter);

    if (result.success) {
      setPreTodayRegistCount(data?.todayRegistCount);
      setData(result);
    }

    return Promise.resolve(result);
  };

  const getMinuteAddText = () => {
    if (data == undefined || preTodayRegistCount == undefined) {
      return ``;
    }
    return (
      <>
        <div style={{ fontSize: 14, color: 'gray' }}>
          +{utils.formatNumber(data.todayRegistCount - preTodayRegistCount)}
        </div>
      </>
    );
  };

  const getActiveStatText = () => {
    if (data == undefined) {
      return `0 / 0`;
    }
    return `${utils.formatNumber(data.activeStat.t7)} / ${utils.formatNumber(
      data.activeStat.t30,
    )}`;
  };
  const getActiveStat3DayText = () => {
    if (data == undefined) {
      return `--`;
    }
    return `${utils.formatNumber(data.activeStat.t0)} / ${utils.formatNumber(
      data.activeStat.t1,
    )} / ${utils.formatNumber(data.activeStat.t2)} / ${utils.formatNumber(
      data.activeStat.t3,
    )} / ${utils.formatNumber(data.activeStat.t4)} / ${utils.formatNumber(
      data.activeStat.t5,
    )} / ${utils.formatNumber(data.activeStat.t6)} / ${utils.formatNumber(
      data.activeStat.t8,
    )}`;
  };

  let columns: ProColumns<API.UserCountryStat>[] = [
    {
      title: '小时',
      // width: 200,
      hideInTable: !(statHour && activeGenre == '1d'),
      dataIndex: 'hour',
    },
    {
      title: '名称', //activeGenre == "all" ? statAllType == "2" ? "平台" : statAllType == "3" ? "客户端版本" : "国家" : "国家",
      // width: 200,
      hideInTable: statHour && activeGenre == '1d',
      dataIndex: 'country',
    },
    {
      title: '数量',
      // width: 200,
      dataIndex: 'count',
      render: (_, record) => {
        return utils.formatNumber(record.count);
      },
    },
    {
      title: '占比',
      // width: 200,
      // hideInTable:statAllType == "2" && activeGenre == "all",
      dataIndex: 'count',
      render: (_, record) => {
        return `${((record.count * 100) / (data?.activeTotal ?? 1)).toFixed(
          2,
        )}%`;
      },
    },
    {
      title: '日活数量',
      hideInTable: (
        activeGenre == '1d'
      ),
      dataIndex: 'dayCount',
      render: (_, record) => {
        return utils.formatNumber(record.dayCount);
      },
    },
    {
      title: '日活占比',
      hideInTable: (
        activeGenre == '1d'
      ),
      dataIndex: 'dayCount',
      render: (_, record) => {
        return `${
          data?.dayTotal
            ? (((record.dayCount ?? 0) * 100) / (data?.dayTotal ?? 1)).toFixed(
                2,
              )
            : 0
        }%`;
      },
    },
    {
      title: '日活/数量比',
      hideInTable: (
        activeGenre == '1d'
      ),
      dataIndex: 'dayCount',
      render: (_, record) => {
        return `${
          data?.dayTotal
            ? (((record.dayCount ?? 0) * 100) / (record?.count ?? 1)).toFixed(2)
            : 0
        }%`;
      },
    },
  ];

  let registColumns: ProColumns<API.RegistStat>[] = [
    {
      title: '日期',
      align: 'center',
      width: 180,
      dataIndex: 'date',
      valueType: 'date',
    },
    {
      title: '合计',
      align: 'center',
      dataIndex: 'total',
      render: (_, record) => {
        return utils.formatNumber(record.total);
      },
    },
    {
      title: '苹果',
      align: 'center',
      dataIndex: 'ios',
      render: (_, record) => {
        return utils.formatNumber(record.ios);
      },
    },
    {
      title: '安卓',
      align: 'center',
      dataIndex: 'android',
      render: (_, record) => {
        return utils.formatNumber(record.android);
      },
    },
    {
      title: '安卓(GooglePlay)',
      align: 'center',
      dataIndex: 'androidGoogle',
      render: (_, record) => {
        return utils.formatNumber(record.androidGoogle);
      },
    },
    {
      title: '安卓(APK)',
      align: 'center',
      dataIndex: 'androidUniversal',
      render: (_, record) => {
        return utils.formatNumber(record.androidUniversal);
      },
    },
    {
      title: '苹果占比',
      dataIndex: 'count',
      width: 100,
      render: (_, record) => {
        return `${((record.ios * 100) / record.total).toFixed(2)}%`;
      },
    },
    {
      title: '安卓占比',
      dataIndex: 'count',
      width: 100,
      render: (_, record) => {
        return `${((record.android * 100) / record.total).toFixed(2)}%`;
      },
    },
    {
      title: 'GooglePlay/安卓',
      dataIndex: 'count',
      width: 130,
      render: (_, record) => {
        return `${((record.androidGoogle * 100) / record.android).toFixed(2)}%`;
      },
    },
    {
      title: 'APK/安卓',
      dataIndex: 'count',
      width: 100,
      render: (_, record) => {
        return `${((record.androidUniversal * 100) / record.android).toFixed(
          2,
        )}%`;
      },
    },
  ];

  return (
    <MyContent>
      <Card
        extra={
          <Space>
            <Countdown
              title=""
              key="cdRefresh"
              value={countdownTicks}
              format="s"
              prefix=""
              suffix="秒后刷新"
              valueStyle={{
                fontSize: 14,
                color: 'gray',
              }}
              onFinish={reload}
            />
            <ReloadOutlined onClick={reload} />
          </Space>
        }
        style={{ marginBottom: 20 }}
        tabList={[
          { tab: '注册统计', key: 'regist' },
          { tab: '日活跃', key: '1d' },
          { tab: '7天活跃', key: '7d' },
          { tab: '30天活跃', key: '30d' },
          { tab: '总用户', key: 'all' },
        ]}
        activeTabKey={activeGenre}
        onTabChange={(key: string) => {
          setActiveGenre(key as string);
        }}
      >
        <Row gutter={16}>
          <Col span={2}>
            <Statistic
              title="当前在线"
              value={utils.formatNumber(data?.currentConnCount)}
            />
          </Col>
          <Col span={2}>
            <Statistic
              title="今日新增"
              value={utils.formatNumber(data?.todayRegistCount)}
              suffix={getMinuteAddText()}
            />
          </Col>
          <Col span={2}>
            <Statistic
              title="总用户"
              value={utils.formatNumber(data?.totalUser)}
            />
          </Col>
          <Col span={3}>
            <Statistic title="周活跃用户(本周/上周)" value={getActiveStatText()} />
          </Col>
          <Col span={3}>
            <Statistic title="月活跃用户(本月/上月)" value={getActiveStatText()} />
          </Col>
          {/* <Col span={3}>
            <Statistic title="活跃用户(周/月)" value={getActiveStatText()} />
          </Col> */}
          {/* <Col span={11}>
            <Statistic
              title="活跃用户(今天/昨天/前天/3天前/4天前/5天前/6天前/7天前)"
              value={getActiveStat3DayText()}
            />
          </Col> */}
        </Row>
        <Row gutter={16}>
          <Col span={11}>
            <Statistic
              title="活跃用户(今天/昨天/前天/3天前/4天前/5天前/6天前/7天前)"
              value={getActiveStat3DayText()}
            />
          </Col>
        </Row>
      </Card>

      <ProTable
        rowKey="id"
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        style={{
          visibility: activeGenre == 'regist' ? 'hidden' : 'visible',
          height: activeGenre == 'regist' ? 0 : undefined,
        }}
        columnEmptyText={''}
        actionRef={actionRef}
        formRef={formRef}
        columns={columns}
        search={false}
        pagination={false}
        params={{
          genre: activeGenre,
          statDay: statDay,
          statHour: statHour,
          statAllType: statAllType,
        }}
        request={loadData}
        toolbar={{
          multipleLine: true,
          filter: (
            <LightFilter style={{ textAlign: 'right' }}>
              <Tag
                color="blue"
                style={{
                  visibility: activeGenre == 'regist' ? 'hidden' : 'visible',
                }}
              >
                <b>总数量：{data?.activeTotal}</b>
              </Tag>

              <Space
                style={{
                  // visibility: activeGenre == 'all' ? 'visible' : 'hidden',
                  marginRight:50
                }}
              >
                <Tabs
                  activeKey={statAllType}
                  style={{marginTop:-50}}
                  items={[
                    { label: '按国家统计', key: '1' },
                    { label: '按平台统计', key: '2' },
                    { label: '按版本统计', key: '3' },
                  ]}
                  onChange={(activeKey) => {
                    setStatAllType(activeKey);
                  }}
                ></Tabs>
              </Space>

              <Space
                style={{
                  visibility: activeGenre == '1d' ? 'visible' : 'hidden',
                  width: activeGenre == '1d' ? 550 : 0,
                }}
              >
                <Tabs
                  tabBarExtraContent={
                    <div style={{ marginRight: 10 }}>
                      <ProFormSwitch
                        name="swHour"
                        initialValue={statHour}
                        label="小时活跃[国家]"
                        fieldProps={{
                          onChange: (val) => {
                            // console.log(val);
                            setStatHour(val);
                          },
                        }}
                      />
                    </div>
                  }
                />

                <Tabs
                  tabBarExtraContent={
                    <div style={{ marginRight: 20 }}>
                      <ProFormDatePicker
                        label="统计日期"
                        name="statDate"
                        allowClear={false}
                        initialValue={statDay}
                        fieldProps={{
                          onChange(value, dateString) {
                            // console.log(value, dateString,value?.format("yyyy-MM-DD"));
                            setStatDay(value?.format('yyyy-MM-DD'));
                          },
                        }}
                      />
                    </div>
                  }
                />

                <Tabs
                  activeKey={statDay}
                  items={[
                    { label: '今天', key: moment().format('yyyy-MM-DD') },
                    {
                      label: '昨天',
                      key: moment().add(-1, 'day').format('yyyy-MM-DD'),
                    },
                    {
                      label: '前天',
                      key: moment().add(-2, 'day').format('yyyy-MM-DD'),
                    },
                  ]}
                  onChange={(activeKey) => {
                    // console.log(activeKey);
                    setStatDay(activeKey);
                    // formRef.current?.setFieldValue("statDate", statDay);
                  }}
                ></Tabs>
              </Space>
            </LightFilter>
          ),
          // menu: {
          //   type: 'tab',
          //   activeKey: activeGenre,
          //   items: [{label:"注册统计", key:"regist"},{label:"日活跃", key:"1d"},{label:"7天活跃", key:"7d"},{label:"30天活跃", key:"30d"},{label:"总用户", key:"all"}],
          //   onChange: (key) => {
          //     setActiveGenre(key as string);
          //     // if(key == "1d"){
          //     //   setSubTabData(dayTabs);
          //     // }
          //     // else{
          //     //   setSubTabData([]);
          //     // }
          //   },
          // },
          // tabs: {
          //   activeKey: activeDay,
          //   items: subTabData,
          //   onChange: (key) => {
          //     setActiveDay(key)
          //   },
          // },
        }}
      />

      <ProTable
        rowKey="id"
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        style={{
          visibility: activeGenre == 'regist' ? 'visible' : 'hidden',
          height: activeGenre == 'regist' ? undefined : 0,
        }}
        columnEmptyText={''}
        actionRef={actionRef}
        formRef={formRef}
        columns={registColumns}
        search={false}
        pagination={false}
        params={{
          genre: activeGenre,
          statDay: statDay,
          statHour: statHour,
          statAllType: statAllType,
        }}
        dataSource={data?.registStat}
      />
    </MyContent>
  );
};

export default List;
